<template>
  <div class="page-container brand-form">
    <el-form class="el-form-modify" ref="form" label-width="80px" :model="formData" :rules="rules">
      <el-form-item label="品牌名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入品牌名称" />
      </el-form-item>
      <el-form-item label="品牌商标" prop="logo">
        <upload-image v-model="formData.logo" :uploadUrl="uploadBrandUrl">
        </upload-image>
      </el-form-item>
      <el-form-item label="品牌备注" prop="remark">
        <el-input
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 8}"
          placeholder="请输入品牌备注"
          v-model="formData.remark">
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save" size="small" :loading="saving">保存</el-button>
        <el-button @click="cancel" size="small">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import UploadImage from '@/components/UploadImage';
import {brandPathPrefix} from '@/settings';
import {brandAdd, brandDetail, brandEdit, uploadBrandUrl} from '@/api/brand'
import {rules} from '@/utils/validate'

export default {
  name: 'EquityForm',
  components: {
    uploadImage: UploadImage
  },
  data() {
    this.uploadBrandUrl = uploadBrandUrl;

    return {
      pathPrefix: brandPathPrefix,
      formData: {
        name: '',
        logo: '',
        remark: ''
      },
      rules: {
        name: [rules.required, rules.text2_18],
        logo: [
          // { required: true, message: '请上传品牌图标', trigger: 'change' },
        ],
        remark: [rules.textMax_128]
      },
      saving: false
    }
  },
  methods: {
    async requestDetail(id) {
      try {
        const {data} = await brandDetail(id)
        if (data) {
          this.formData = {...data}
        } else {
          this.cancel();
        }
      } catch(err) {
        this.cancel();
      }
    },
    save() {
      this.$refs.form.validate(async(valid) => {
        if (!valid) {
          return;
        }
        try {
          this.saving = true;
          const method = this.formData.id ? brandEdit : brandAdd
          await method(this.formData)
          this.saving = false;
          this.$message.success('保存成功!');
          this.$emit('refresh');
          this.cancel();
        } catch(err) {
          this.saving = false;
        }
      })
    },
    cancel() {
      this.$router.push({name: 'brandMgt'});
    }
  },
  created() {
    if (this.$route.name === 'editBrand') {
      let {id} = this.$route.params;
      if (id) {
        this.requestDetail(id);
      } else {
        this.cancel();
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.page-container.brand-form{
  margin: 0;
  padding: 20px 0 0 0;
}
</style>